var ws = require('nodejs-websocket')
var Cesium = require('cesium')
var moment = require('moment')


var PORT = 3006
function getAngel(A, B) {
    var dx = (B.m_RadLo - A.m_RadLo) * A.Ed;
    var dy = (B.m_RadLa - A.m_RadLa) * A.Ec;
    var angle = 0.0;
    angle = (Math.atan(Math.abs(dx / dy)) * 180) / Math.PI;
    var dLo = B.m_Longitude - A.m_Longitude;
    var dLa = B.m_Latitude - A.m_Latitude;
    if (dLo > 0 && dLa <= 0) {
        angle = 90 - angle + 90;
    } else if (dLo <= 0 && dLa < 0) {
        angle = angle + 180;
    } else if (dLo < 0 && dLa >= 0) {
        angle = 90 - angle + 270;
    }
    return angle;
}
function MyLatLng(longitude, latitude) {
    var Rc = 6378137;
    var Rj = 6356725;
    var m_LoDeg, m_LoMin, m_LoSec;
    var m_LaDeg, m_LaMin, m_LaSec;
    var m_Longitude, m_Latitude;
    var m_RadLo, m_RadLa;
    var Ec;
    var Ed;
    m_LoDeg = longitude;
    m_LoMin = Number.parseInt((longitude - m_LoDeg) * 60);
    m_LoSec = (longitude - m_LoDeg - m_LoMin / 60) * 3600;
    m_LaDeg = latitude;
    m_LaMin = Number.parseInt((latitude - m_LaDeg) * 60);
    m_LaSec = (latitude - m_LaDeg - m_LaMin / 60) * 3600;
    m_Longitude = longitude;
    m_Latitude = latitude;
    m_RadLo = (longitude * Math.PI) / 180;
    m_RadLa = (latitude * Math.PI) / 180;
    Ec = Rj + ((Rc - Rj) * (90 - m_Latitude)) / 90;
    Ed = Ec * Math.cos(m_RadLa);
    return {
        m_RadLo: m_RadLo,
        m_RadLa: m_RadLa,
        m_Longitude: m_Longitude,
        m_Latitude: m_Latitude,
        Ed: Ed,
        Ec: Ec,
    };
}

// 时间加一秒
function dateAdd(d, num) {
    var d = new Date(
        d.substring(0, 4),
        d.substring(5, 7) - 1,
        d.substring(8, 10),
        d.substring(11, 13),
        d.substring(14, 16),
        d.substring(17, 19)
    );
    d.setTime(d.getTime() + num * 1000);
    return (
        d.getFullYear() +
        "-" +
        checkTime(d.getMonth() + 1) +
        "-" +
        checkTime(d.getDate()) +
        " " +
        checkTime(d.getHours()) +
        ":" +
        checkTime(d.getMinutes()) +
        ":" +
        checkTime(d.getSeconds())
    );
}
function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function boradcast(msg) {
    server.connections.forEach(item => {
        item.send(JSON.stringify(msg))
        //
        // item.send(JSON.stringify(obj))
    })
}

// 距离计算
function distance(point1, point2) {
    var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
    var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
    /**根据经纬度计算出距离**/
    var geodesic = new Cesium.EllipsoidGeodesic();
    geodesic.setEndPoints(point1cartographic, point2cartographic);
    var s = geodesic.surfaceDistance;
    //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
    //返回两点之间的距离
    s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
    return s;
}


// 任务
var taskProgressArr = {
    deviceName: "翼龙无人机",
    taskName: "打击敌方3号目标阵地",
    speed: "",
    duration: 15 * 60,
    children: [
        {
            id: 1,
            state: "任务已下发",
            startTime: "2022-12-12 12:00:00",
            status: 1,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,

            isfly: "待机",
            lon: 97.0208,
            lat: 29.3544,
            height: 0,
        },
        {
            id: 2,
            state: "任务前监测",
            startTime: "2022-12-12 12:01:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,

            isfly: "待机",
            lon: 97.0208,
            lat: 29.3544,
            height: 0,
        },
        {
            id: 3,
            state: "无人机起飞",
            startTime: "2022-12-12 12:02:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,

            isfly: "飞行中",
            lon: 97.0208,
            lat: 29.3544,
            height: 0,
        },
        {
            id: 4,
            state: "无人机抵达航线1",
            startTime: "2022-12-12 12:03:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            isfly: "飞行中",
            lon: 97.0573,
            lat: 29.2547,
            height: 1000,
        },

        {
            id: 5,
            state: "无人机抵达航线2",
            startTime: "2022-12-12 12:04:00",
            endTime: "2022-12-12 12:05:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            isfly: "飞行中",
            lon: 97.0617,
            lat: 29.1693,
            height: 2000,
        },
        {
            id: 6,
            state: "无人机抵达航线3",
            startTime: "2022-12-12 12:05:00",
            endTime: "2022-12-12 12:06:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            isfly: "飞行中",
            lon: 97.1022,
            lat: 29.1364,
            height: 2500,
        },
        {
            id: 7,
            state: "无人机抵达航线4",
            startTime: "2022-12-12 12:06:00",
            endTime: "2022-12-12 12:07:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 3000,
            isfly: "飞行中",
            lon: 97.0938,
            lat: 29.0596,
        },
        {
            id: 8,
            state: "无人机抵达航线5",
            startTime: "2022-12-12 12:07:00",
            endTime: "2022-12-12 12:08:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 3000,
            isfly: "飞行中",
            lon: 97.1222,
            lat: 29.0404,
        },
        {
            id: 9,
            state: "无人机发现目标",
            startTime: "2022-12-12 12:08:00",
            endTime: "2022-12-12 12:09:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 2200,
            isfly: "飞行中",
            lon: 97.1676,
            lat: 29.0459,
        },
        {
            id: 10,
            state: "无人机进入可攻击范围内",
            startTime: "2022-12-12 12:09:00",
            endTime: "2022-12-12 12:10:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 2100,
            isfly: "飞行中",
            lon: 97.1504,
            lat: 28.9863,
        },
        {
            id: 11,
            state: "无人机瞄准目标",
            startTime: "2022-12-12 12:10:00",
            endTime: "2022-12-12 12:11:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 2000,
            isfly: "飞行中",
            lon: 97.1514,
            lat: 28.9863,
        },
        {
            id: 12,
            state: "无人机开始打击目标",
            startTime: "2022-12-12 12:11:00",
            endTime: "2022-12-12 12:12:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 2000,
            isfly: "飞行中",
            lon: 97.1504,
            lat: 28.9863,
        },
        {
            id: 13,
            state: "无人机完成打击目标",
            startTime: "2022-12-12 12:12:00",
            endTime: "2022-12-12 12:13:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 2000,
            isfly: "飞行中",
            lon: 97.1983,
            lat: 28.9948,
        },
        {
            id: 14,
            state: "无人机开始返航",
            startTime: "2022-12-12 12:13:00",
            endTime: "2022-12-12 12:14:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 1000,
            isfly: "飞行中",
            lon: 97.1983,
            lat: 28.9948,
        },
        {
            id: 15,
            state: "无人机回到发射地",
            startTime: "2022-12-12 12:14:00",
            endTime: "2022-12-12 12:15:00",
            status: 0,
            fengsu: 5.6,
            wendu: 22,
            qixiang: "小雨",
            daikuan: 8.5,
            dianliang: 88,
            xuhang: 3 * 60 * 60,
            speed: 0,
            height: 0,
            isfly: "待机",
            lon: 97.0208,
            lat: 29.3544,
        },
    ],
}
// 开始时间
var startTime = '2022-12-12 12:00:00'
// 当前时间
var nowTime = startTime
// 无人机飞行路径差值点
var allPoints = [];
// 电池电量
var dianliang = 100

taskProgressArr.children.forEach((v, i) => {

    if (i < taskProgressArr.children.length - 1) {
        var controls = [];
        controls.push(
            Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height),
            Cesium.Cartesian3.fromDegrees(
                taskProgressArr.children[i + 1].lon,
                taskProgressArr.children[i + 1].lat,
                taskProgressArr.children[i + 1].height
            )
        );
        let duration = moment(taskProgressArr.children[i + 1].startTime).diff(
            moment(v.startTime),
            "second"
        );
        // let duration = 6;
        // console.log(duration, "时长，秒");

        let times = [];
        for (let i = 0; i < controls.length; i++) {
            times.push((1 / (controls.length - 1)) * i);
        }

        // console.log(times);

        var spline = new Cesium.LinearSpline({
            times: times,
            points: controls,
        });
        //   插值50个点
        var positions = [];
        for (var i = 0; i <= duration; i++) {
            var cartesian3 = spline.evaluate(i / duration);
            positions.push(cartesian3);
            // viewer.value.entities.add({
            //   position: cartesian3,
            //   point: {
            //     color: Cesium.Color.YELLOW,
            //     pixelSize: 6,
            //   },
            // });
        }

        positions.splice(0, 1);

        allPoints.push(...positions);
    }
});
allPoints.push(
    Cesium.Cartesian3.fromDegrees(
        taskProgressArr.children[0].lon,
        taskProgressArr.children[0].lat,
        taskProgressArr.children[0].height
    )
);

// 无人机所有点和角度
var uavPointArr = []
var uavPo = []
allPoints.forEach((v, i) => {
    uavPo.push(v)
    var jtcx = 0
    if (uavPo.length > 2) {
        uavPo.splice(0, 1);
    }
    if (uavPo.length == 2) {
        var head = 0
        var cartographic = Cesium.Cartographic.fromCartesian(uavPo[0]);
        let lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
        let lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
        let height = cartographic.height.toFixed(4);

        var cartographic1 = Cesium.Cartographic.fromCartesian(uavPo[1]);
        let lon1 = Cesium.Math.toDegrees(cartographic1.longitude).toFixed(4);
        let lat1 = Cesium.Math.toDegrees(cartographic1.latitude).toFixed(4);
        let height1 = cartographic1.height.toFixed(4);
        var ag = getAngel(
            MyLatLng(lon, lat, height),
            MyLatLng(lon1, lat1, height1)
        );
        ag ? head = (-ag * Math.PI) / 180 : 0
        ag ? jtcx = ag : 0
        var jl = distance(uavPo[0], uavPo[1])
        uavPointArr.push({
            position: v,
            head: head,
            jl,
            jtcx: jtcx,
        })
    }
})

console.log(uavPointArr, '无人机所有点和角度', uavPointArr.length);

// console.log(allPoints, '所有点');
let timer;
// 当前任务和下一个任务
var currentTask, nextTask;
//计时器开始
let num = 0;
// 无人机信息
let obj = {}
// 
let flag = false

// 目标
var targetObj = {}
// 导弹
let targetPo = []
var target = {
    isShow: false,
    lon: 97,
    lat: 29,
    height: 0,
    id: "target"
}


var targetcontrols = [];
//导弹所有路径点插值
var targetAllPoint = []

targetcontrols.push(
    Cesium.Cartesian3.fromDegrees(97.1514, 28.9863, 2000),//发射点
    Cesium.Cartesian3.fromDegrees(97, 29, 0),//目标位置
);

let times = [];
for (let i = 0; i < targetcontrols.length; i++) {
    times.push((1 / (targetcontrols.length - 1)) * i);
}
var spline = new Cesium.LinearSpline({
    times: times,
    points: targetcontrols,
});
//   插值50个点
var positions = [];
for (var i = 0; i <= 60; i++) {
    var cartesian3 = spline.evaluate(i / 60);
    targetAllPoint.push(cartesian3);
}
// 导弹所有插值点和角度
let nextArr = []

targetAllPoint.forEach((v, i) => {

    targetPo.push(v);
    if (targetPo.length > 2) {
        targetPo.splice(0, 1);
    }
    if (targetPo.length == 2) {
        var thead = 0
        var cartographic = Cesium.Cartographic.fromCartesian(targetPo[0]);
        let lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
        let lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
        let height = cartographic.height.toFixed(4);
        var cartographic1 = Cesium.Cartographic.fromCartesian(targetPo[1]);
        let lon1 = Cesium.Math.toDegrees(cartographic1.longitude).toFixed(4);
        let lat1 = Cesium.Math.toDegrees(cartographic1.latitude).toFixed(4);
        let height1 = cartographic1.height.toFixed(4);
        var ag = getAngel(
            MyLatLng(lon, lat, height),
            MyLatLng(lon1, lat1, height1)
        );
        // console.log(ag);
        ag ? thead = (-ag * Math.PI) / 180 : 0
        ag ? sss = ag : 0
        nextArr.push({
            position: v,
            head: thead
        })
    }


})

console.log(nextArr.length, 8888);
let targetNum = 0
let fashe = {
    messageType: "fashe",
    data: {}
}

// 爆炸
var baozha = {}
var faIsShow = false
var bzIsShow = false
timer = setInterval(() => {
    // if (!flag) return
    nowTime = dateAdd(nowTime, 1);
    // 发射
    if (targetNum >= nextArr.length - 1) {
        targetNum = nextArr.length - 1
    } else {
    }


    if (new Date(nowTime).getTime() >= new Date('2022-12-12 12:11:00').getTime() && new Date(nowTime).getTime() <= new Date('2022-12-12 12:12:00').getTime()) {
        faIsShow = true
        fashe.data = {
            position: nextArr[targetNum].position,
            head: nextArr[targetNum].head,
        }
        targetNum++
    } else {

        faIsShow = false
    }

    // 发现目标
    if (nowTime == '2022-12-12 12:11:00') {
        target.isShow = true
    }
    if (new Date(nowTime).getTime() > new Date('2022-12-12 12:12:00').getTime()) {
        console.log('iffff');
        target.isShow = false
    }
    if (nowTime == '2022-12-12 12:12:00') {
        bzIsShow = true
        baozha.messageType = 'baozha',
            baozha.data = target
    } else {
        bzIsShow = false
    }
    targetObj = {
        messageType: 'setTarget',
        data: target
    }


    // 当前任务和下个任务

    taskProgressArr.children.forEach((v) => {
        if (new Date(v.startTime).getTime() <= new Date(nowTime)) {
            currentTask = v;
        }
    });

    let index = taskProgressArr.children.findIndex((v) => {
        return v.id == currentTask.id;
    });
    if (index < taskProgressArr.children.length - 1) {
        nextTask = taskProgressArr.children[index + 1];
        dianliang = Number((dianliang - 0.01).toFixed(2))
    } else if (index == taskProgressArr.children.length - 1) {
        nextTask = false
    }

    if (num > uavPointArr.length - 1) {

        num = uavPointArr.length - 1
    }

    let zjl = distance(allPoints[0], allPoints[num])
    // console.log(zjl, '距离云台');

    var cartographic = Cesium.Cartographic.fromCartesian(allPoints[num]);
    var ldgd = cartographic.height; // 的值为地形高度

    let data = {
        position: uavPointArr[num].position,
        head: uavPointArr[num].head,
        nowTime,
        startTime,
        currentTask,
        nextTask,
        ldgd: ldgd.toFixed(3),
        jl: uavPointArr[num].jl.toFixed(3),
        allPoints,
        zjl: zjl.toFixed(3),
        jtcx: uavPointArr[num].jtcx,
        dianliang
    }

    obj = {
        messageType: 'setPosition',
        data
    }

    num++

}, 1000);

var server = ws
    .createServer(function (conn) {
        console.log('链接成功');
        flag = true
        let obj1 = {
            messageType: "setTask",
            data: taskProgressArr
        }
        // conn.send(JSON.stringify(obj1))
        boradcast(obj1)
        conn.on('close', function (code, reason) {
            console.log('Connection closed')
        })
        conn.on('error', function (err) {
            console.log('handle err')
            console.log(err)
        })

        conn.on('text', function (str) {
            console.log(str, '接收的信息');
            // conn.send(JSON.stringify(obj))
            setInterval(() => {

                boradcast(obj)
                if (target.isShow) {
                    boradcast(targetObj)
                }
                if (faIsShow) boradcast(fashe)
                if (bzIsShow) boradcast(baozha)
            }, 1000);
        })

    })
    .listen(PORT)
